import iconv from "iconv-lite";
import axios from 'axios';
import fetch from "isomorphic-fetch"
const instance = axios.create({
    // ...其他配置
});

// 添加响应拦截器
instance.interceptors.response.use(
    response => {
        // 如果响应头中包含charset=gbk，则进行解码
        const contentType = response.headers['Content-Type'] || response.headers['content-type'];
        // 解析Content-Type头以获取字符集
        if (contentType) {
            const charset = contentType.match(/charset=([\w-]+)/i)?.pop();
            response.data = iconv.decode(response.data, charset);
        }
        return response;
    },
    error => {
        // 错误处理
        return Promise.reject(error);
    }
);
/**
 * 请求方法
 * @param {string} url 
 * @returns 
 */
function request(_, url, options = {}) {
    const {
        method = 'GET',
    } = options;
    return fetch(url,
        {
            method,
            headers: {
                accept: `text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9`,
                'accept-encoding': 'gzip, deflate, br',
                'accept-language': 'zh-CN,zh;q=0.9',
                'cache-control': 'max-age=0',
                cookie: `UM_distinctid=19719b15ce21b9-04af948e4b067c-26021d51-15f900-19719b15ce3120; visitor_id=6842a21515814; cf_chl_rc_ni=1; cf_clearance=JvHgGmx9TxaUOzAsSKZTHqZ5umwjN4Nsq7Cyl1U6tVg-1749197618-1.2.1.1-c6f3P.prXPG5TrKt3kjBaP_Sf2ZNl1qz6DNDi6ie1iGCjg4Nr4S5S_hF3WLHins20CIdIDfSVjEWmBPlD05SIJzvXfwaQU3vjRB_vnfvqKpLm8xm2TxG2qRjqhLI10iUew_1ALum2PQShHUxvSBOp.H8nGN1VWWSImlnWLjJyky8QVR14PDjs8uN3DTjbKWdTOR_oymsnzrlz7ZsCKmpfT_lPytKKqkhGUu7g3kTRLAAwhizyqWrp6lD9J89vZBRDT.qS3A4hmEW5feNuRuHN7o0aGKFIoFnFnVKUx_UsDxFP.8WlZSkUEQZpKXHG9kO0qeWOplp62OdGiyVf5IMAqsxjE6odizjRNXnHhMG2jXS7Ygk37Cq2Vx8S4GqdQpB; CNZZDATA1281409222=678381003-1748482744-null%7C1749197709`,
                // referer: url,
                'sec-ch-ua':`"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"`,
                'sec-ch-ua-arch': "x86",
                'sec-ch-ua-bitness': "64",
                'sec-ch-ua-full-version': "104.0.5112.81",
                'sec-ch-ua-full-version-list': `"Chromium";v="104.0.5112.81", " Not A;Brand";v="99.0.0.0", "Google Chrome";v="104.0.5112.81"`,
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-model': "",
                'sec-ch-ua-platform': "Windows",
                'sec-ch-ua-platform-version': "10.0.0",
                'sec-fetch-dest': 'document',
                'sec-fetch-mode': 'navigate',
                'sec-fetch-site': 'same-origin',
                'sec-fetch-user': '?1',
                'upgrade-insecure-requests': '1',
                'user-agent': `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36`
            }
        }
    ).then(async res => {
        const buffer = await res.arrayBuffer();
        const decoder = new TextDecoder('utf-8'); // 先用UTF-8解码前部分

        // 只解码前1024字节足够找到meta charset
        const partialText = decoder.decode(buffer.slice(0, 1024));
        const charset = res.headers.get('Content-Type')?.match(/charset=([\w-]+)/i)?.pop() || partialText.match(/charset=([\w-]+)/i)?.pop();
        // 输出字符集
        const bufferArr = Buffer.from(buffer);
        const utf8String = iconv.decode(bufferArr, charset || 'utf-8');
        return utf8String;
    })
}

export default request;